package com.ma.implatform.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ma.common.utils.JwtUtil;
import com.ma.implatform.config.props.JwtProperties;
import com.ma.implatform.enums.ResultCode;
import com.ma.implatform.exception.GlobalException;
import com.ma.implatform.session.UserSession;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
@Slf4j
@Component
@AllArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {
    private final JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         if(!(handler instanceof HandlerMethod)){
             return true;
         }
         //从http请求中取出token
         String token = request.getHeader("accessToken");
         if (StrUtil.isEmpty(token)){
             log.error("未登录，url:{}",request.getRequestURI());
             throw new GlobalException(ResultCode.NO_LOGIN);
         }
        String strJson = JwtUtil.getInfo(token);
        UserSession session = JSON.parseObject(strJson, UserSession.class);
        //验证 token
        if (!JwtUtil.checkSign(token,jwtProperties.getAccessTokenSecret())){
            log.error("token已失效，用户：{}",session.getUserName());
            log.error("token:{}",token);
            throw new GlobalException(ResultCode.INVALID_TOKEN);
        }
        request.setAttribute("session",session);
        return true;
    }
}
